<?php
namespace App\Service\Xcx\Mall;

class CartService extends BaseService
{
    //购物车

    /**
     * 列表
     * @param int $uid
     * @param array $pages【start，limit】
     */
    public static function getList($uid, $pas)
    {
        $start = ($pas['start'] - 1) * $pas['limit'];
        $db = self::dbConn(self::$dbMallCart)
            ->where('del', 0)
            ->where('order_id', 0)
            ->where('uid', $uid);
        $total = $db->count();
        $res = $db->skip($start)->take($pas['limit'])
            ->orderBy('id', 'desc')
            ->get();
        if (!count($res)) {
            return self::toback(0, '', [], $total);
        }
        foreach ($res as &$v) {
            $gOne = self::dbConn(self::$dbMallGoods)->where('id', $v->gid)->first();
            $shop_id = $gOne ? $gOne->shop_id : 0;
            $shopOne = self::dbConn(self::$dbMallShop)->where('id', $shop_id)->first();
            $v->gname = $gOne ? $gOne->title : '-';
            $v->gimg = $gOne&&file_exists($gOne->cover) ? env('DOMAIN') . '/' . $gOne->cover : '';
            $v->gprice = $gOne ? $gOne->price : 0;
            $v->gnum = $v->num;
            $v->shop_name = $shopOne ? $shopOne->shop_name : '-';
        }
        return self::toback(0, '', $res, $total);
    }

    //添加
    public static function add($ary)
    {
        $res = self::dbConn(self::$dbMallCart)
            ->where('del', 0)
            ->where('order_id', 0)
            ->where('uid', $ary['uid'])
            ->where('gid', $ary['gid'])
            ->first();
        $backData = [];
        if ($res) {
            $upData['uptime'] = toDate();
            $upData['num'] = $res->num + $ary['num'];
            self::dbConn(self::$dbMallCart)->where('id', $res->id)->update($upData);
            $backData['num'] = $upData['num'];
        } else {
            $ary['addtime'] = toDate();
            self::dbConn(self::$dbMallCart)->insertGetId($ary);
            $backData['num'] = $ary['num'];
        }
        return self::toback(0, '', $backData);
    }

    //减少
    public static function reduce($ary)
    {
        $res = self::dbConn(self::$dbMallCart)
            ->where('del', 0)
            ->where('order_id', 0)
            ->where('uid', $ary['uid'])
            ->where('gid', $ary['gid'])
            ->first();
        if (!$res) {
            return self::toback(-2, '购物车商品不存在');
        }
        if (!$res->num) {
            return self::toback(-2, '数量不足');
        }
        $upData['num'] = $res->num - 1;
        if (!$upData['num']) {
            $upData['del'] = 1;
        }
        self::dbConn(self::$dbMallCart)->where('id', $res->id)->update($upData);
        $backData['num'] = $upData['num'];
        return self::toback(0, '', $backData);
    }
}